package com.winit.openapi.apiadapter.adapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.oms.spi.intelligent.recommend.command.IntelligentWarehouseReportCommand;
import com.winit.oms.spi.intelligent.recommend.vo.IntelligentWarehouseMerchandise;
import com.winit.oms.spi.intelligent.recommend.vo.IntelligentWarehouseReport;
import com.winit.oms.spi.outbound.IntelligentWarehouseReportService;
import com.winit.oms.spi.outbound.OutboundIntelligentWarehouseService;
import com.winit.oms.spi.outbound.command.order.IntelligentWarehouseCommand;
import com.winit.oms.spi.outbound.vo.OutboundOrderIntelligentWarehouseResult;
import com.winit.oms.spi.outbound.vo.OutboundOrderIntelligentWarehouseVo;
import com.winit.oms.spi.outbound.vo.OutboundOrderVo;
import com.winit.oms.spi.outbound.vo.order.OutboundOrderMerchandiseVo;
import com.winit.oms.spi.vo.v2.order.ProductInfo;
import com.winit.openapi.apiadapter.controller.builder.OrderAdapteBuilder;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.pms.spi.v2.instance.pscInstance.ProductInstanceService;
import com.winit.ums.spi.user.UserBusinessConfService;
import com.winit.ums.spi.user.command.QueryAreaCustomerCommand;
import com.winit.ums.spi.user.command.VildaiteIntelligentRecommendCommand;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.warehouse.WarehouseService;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * 智能推荐
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * hui.li2 	1.0  		2017年1月10日 	Created
 *
 * </pre>
 * @since 1.
 */
@Service("outboundOrderIntelligentServiceAdapter")
public class OutboundOrderIntelligentServiceAdapter {

    private static final Logger                 logger = LoggerFactory.getLogger(OutboundOrderIntelligentServiceAdapter.class);
    @Resource
    private OutboundIntelligentWarehouseService outboundIntelligentWarehouseService;
    @Resource
    private UserBusinessConfService             userBusinessConfService;
    @Resource
    private IntelligentWarehouseReportService   intelligentWarehouseReportService;
    @Resource
    private ProductInstanceService              productInstanceService;
    @Resource
    private WarehouseService                    upsWarehouseService;
    @Resource
    private OrderAdapteBuilder                  orderAdapteBuilder;

    public boolean vildaiteIntelligentRecommend(String cstomerCode, String classCode) {
        VildaiteIntelligentRecommendCommand command = new VildaiteIntelligentRecommendCommand();
        command.setUserCode(cstomerCode);
        command.setClassCode(classCode);
        return userBusinessConfService.vildaiteIntelligentRecommend(command);
    }

    public void getIntelligentRecommendOrder(OutboundOrderVo orderVo) {
        IntelligentWarehouseCommand command = new IntelligentWarehouseCommand();
        // 和小李辉确认，可以去掉
        // command.setIsOldProduct(true);
        List<OutboundOrderVo> list = new ArrayList<OutboundOrderVo>();
        list.add(orderVo);
        command.setList(list);
        // 获取系统配置维护的智能推荐支持的仓库
        OutboundOrderIntelligentWarehouseResult result = outboundIntelligentWarehouseService.getIntelligentWarehouseList(command);
        logger.info("智能推荐结果：" + JSON.toJSONString(result));
        // 转换出参
        if (null != result && result.getIntelligentWarehouseList() != null
            && result.getIntelligentWarehouseList().size() > 0) {
            OutboundOrderIntelligentWarehouseVo ooiw = result.getIntelligentWarehouseList().get(0);
            ProductInfo product = ooiw.getIntelligentProductInfo();
            // 查询仓库
            CodeCommand codeCommand = new CodeCommand();
            codeCommand.setCode(ooiw.getIntelligentWarehouseCode());
            WarehouseVo wareHouse = upsWarehouseService.queryWarehouseByCode(codeCommand);
            if (wareHouse == null) {
                logger.error("getIntelligentRecommendOrder error,仓库编码：" + ooiw.getIntelligentWarehouseCode()
                             + "对应的仓库不存在");
                throw new ApiException(ErrorCode.API_ADAPTE_WAREHOUSE_NOT_EXISTS, ooiw.getIntelligentWarehouseCode());
            }
            if (StringUtils.isNotBlank(product.getWinitProductCode())) {
                if (product.getWinitProductCode().startsWith("OSF")
                    && StringUtils.isNoneBlank(product.getDeliveryCode())) {
                    orderVo.setProductInfo(product);
                    orderVo.setDispatchWarehouseInfo(orderAdapteBuilder.buildWarehouseInfo(wareHouse));
                }
            }

        }

        saveIntelligentWarehouseReport(orderVo, result);

    }

    private void saveIntelligentWarehouseReport(OutboundOrderVo orderVo, OutboundOrderIntelligentWarehouseResult result) {

        try {
            if (result != null) {
                if ((result.getIntelligentWarehouseList() != null && result.getIntelligentWarehouseList().size() > 0)
                    || (result.getStockInsufficientList() != null && result.getStockInsufficientList().size() > 0)) {
                    IntelligentWarehouseReportCommand reportCommand = new IntelligentWarehouseReportCommand();
                    IntelligentWarehouseReport report = new IntelligentWarehouseReport();
                    Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
                    // TODO report.setType();
                    report.setOrderSource(orderVo.getOrderSource());
                    // report.setCustomerCode(orderVo.getCustomerInfo().getCustomerCode());
                    report.setCustomerOrderNo(orderVo.getSellerOrderNo());
                    report.setBuyerName(orderVo.getBuyerInfoVo().getBuyerName());
                    report.setBuyerPhone(orderVo.getBuyerInfoVo().getBuyerPhone());
                    report.setBuyerEmail(orderVo.getBuyerInfoVo().getBuyerEmail());
                    report.setBuyerCountry(orderVo.getBuyerInfoVo().getBuyerCountry());
                    report.setBuyerState(orderVo.getBuyerInfoVo().getBuyerState());
                    report.setBuyerCity(orderVo.getBuyerInfoVo().getBuyerCity());
                    report.setBuyerPostcode(orderVo.getBuyerInfoVo().getBuyerPostcode());
                    report.setBuyerAddress1(orderVo.getBuyerInfoVo().getBuyerAddress1());
                    report.setEbayBuyerId(orderVo.getEbayOrderVo().getEbayBuyerId());
                    report.setEbaySellerId(orderVo.getEbayOrderVo().getEbaySellerId());
                    report.setSourceWarehouseCode(orderVo.getDispatchWarehouseInfo().getWarehouseCode());
                    report.setSourceWarehouseName(orderVo.getDispatchWarehouseInfo().getWarehouseName());
                    report.setSourceProductCode(orderVo.getProductInfo().getWinitProductCode());
                    report.setSourceProductName(orderVo.getProductInfo().getWinitProductName());
                    report.setCurrency("USD");// TODO 默认
                    if (result.getIntelligentWarehouseList() != null && result.getIntelligentWarehouseList().size() > 0) {
                        OutboundOrderIntelligentWarehouseVo inOrderVo = result.getIntelligentWarehouseList().get(0);
                        report.setRecommendWarehouseCode(inOrderVo.getIntelligentWarehouseCode());
                        report.setRecommendWarehouseName(inOrderVo.getIntelligentWarehouseName());
                        report.setRecommendProductCode(inOrderVo.getIntelligentProductInfo().getWinitProductCode());
                        report.setRecommendProductName(inOrderVo.getIntelligentProductInfo().getWinitProductName());
                        report.setRecommendSla(inOrderVo.getIntelligentSlaDays() == null ? null : inOrderVo.getIntelligentSlaDays()
                            .longValue());
                        report.setRecommendFee(inOrderVo.getIntelligentEstimateFees());
                        report.setSourceSla(inOrderVo.getSourceSlaDays() == null ? null : inOrderVo.getSourceSlaDays()
                            .longValue());
                        report.setSourceFee(inOrderVo.getSourceEstimateFees());
                        report.setCustomerCode(inOrderVo.getCustomerInfo().getCustomerCode());
                        report.setErrorMsg(inOrderVo.getErrorMessage());
                    }
                    if (result.getStockInsufficientList() != null && result.getStockInsufficientList().size() > 0) {
                        OutboundOrderIntelligentWarehouseVo stockOrderVo = result.getStockInsufficientList().get(0);
                        report.setNoWarehouseCode(stockOrderVo.getIntelligentWarehouseCode());
                        report.setNoWarehouseName(stockOrderVo.getIntelligentWarehouseName());
                        report.setNoProductCode(stockOrderVo.getIntelligentProductInfo().getWinitProductCode());
                        report.setNoProductName(stockOrderVo.getIntelligentProductInfo().getWinitProductName());
                        report.setNoSla(stockOrderVo.getIntelligentSlaDays() == null ? null : stockOrderVo.getIntelligentSlaDays()
                            .longValue());
                        report.setNoFee(stockOrderVo.getIntelligentEstimateFees());
                        report.setSourceSla(stockOrderVo.getSourceSlaDays() == null ? null : stockOrderVo.getSourceSlaDays()
                            .longValue());
                        report.setSourceFee(stockOrderVo.getSourceEstimateFees());
                        report.setCustomerCode(stockOrderVo.getCustomerInfo().getCustomerCode());
                        report.setErrorMsg(stockOrderVo.getErrorMessage());
                    }
                    List<IntelligentWarehouseMerchandise> merchandiseList = new ArrayList<IntelligentWarehouseMerchandise>();
                    List<OutboundOrderMerchandiseVo> merchandiseInfoList = orderVo.getMerchandiseInfoList();
                    for (OutboundOrderMerchandiseVo merchandiseVo : merchandiseInfoList) {
                        IntelligentWarehouseMerchandise merchandise = new IntelligentWarehouseMerchandise();
                        merchandise.setMerchandiseCode(merchandiseVo.getMerchandiseCode());
                        merchandise.setMerchandiseSerno(merchandiseVo.getMerchandiseSerno());
                        merchandise.setSpecification(merchandiseVo.getSpecification());
                        merchandise.setEbayTransactionId(merchandiseVo.getEbayTransactionId());
                        merchandise.setEbayItemId(merchandiseVo.getEbayItemId());
                        merchandise.setDispatchQty(Long.valueOf(merchandiseVo.getEstimateDispatchQty()));
                        merchandise.setNameCn(merchandiseVo.getNameCn());
                        merchandise.setNameEn(merchandiseVo.getNameEn());
                        merchandiseList.add(merchandise);
                    }
                    report.setMerchandiseList(merchandiseList);
                    report.setCreated(new Date());
                    report.setCreatedby(bpartner.getValue());
                    report.setOrganizationId(Long.valueOf(bpartner.getAdOrgId()));

                    reportCommand.setIntelligentWarehouseReport(report);

                    intelligentWarehouseReportService.createIntelligentWarehouseReport(reportCommand);
                }
            }
        } catch (Exception e) {
            logger.info("save IntelligentWarehouse log error:" + e);
        }
    }

    /**
     * 根据客户编码查询仓库编码列表
     * 
     * @param cstomerCode
     * @return
     */
    public List<String> queryWareHouseByAreaCode(String cstomerCode) {
        QueryAreaCustomerCommand command = new QueryAreaCustomerCommand();
        command.setUserCode(cstomerCode);
        List<String> warehouseList = userBusinessConfService.queryWareHouseByAreaCode(command);

        return warehouseList;
    }

}
